<script setup lang="ts">
import { computed, nextTick, ref, unref } from 'vue';
import type { DrawerPlacement } from 'naive-ui';
import { useMessage } from 'naive-ui';
import { createRoute, getRoute, updateRoute } from '@/service/api';
import Form from '@/components/form/index.vue';
import type { FormItemProps } from '@/components/form/props';
import Modal from './modal.vue';

defineOptions({
  name: 'RouteDrawer'
});

const props = defineProps<{
  routeId: number;
}>();
const modalRef = ref<InstanceType<typeof Modal>>();
const active = ref(false);
const placement = ref<DrawerPlacement>('right');
const loading = ref(false);
const message = useMessage();

const formRef = ref<InstanceType<typeof Form>>();
const permissions = ref<number[]>([]);
const formItems = ref<FormItemProps[]>([
  {
    label: '角色名称：',
    path: 'name',
    component: 'input',
    componentProps: {
      placeholder: '请输入路由名称'
    },
    rules: [
      {
        required: true,
        message: '请输入路由名称'
      }
    ],
    grid: {
      span: 12
    }
  }
]);

const emit = defineEmits<{
  (e: 'refreshList'): void;
}>();

async function handleGetRoute(params: { id: number }) {
  if (params.id <= 0) {
    permissions.value = [];
    return;
  }
  const { data, error } = await getRoute(params);
  if (error) {
    return;
  }
  permissions.value = data?.permissions?.map(item => item.id) || [];
  formRef.value?.setFormValue(data);
}

const activate = () => {
  active.value = true;
  nextTick(async () => {
    await handleGetRoute({ id: props.routeId });
    handleAssign();
  });
};

const gatModelValue = computed(() => {
  return formItems.value.reduce(
    (pre, cur) => {
      pre[cur.path] = '';
      return pre;
    },
    {} as Record<string, string>
  );
});

// 提交
function handleSubmit(e: MouseEvent) {
  formRef.value?.validate(e, valid => {
    if (!valid) {
      return;
    }
    const { name } = formRef.value?.getFormValue() as Api.System.Route;
    if (!name) {
      return;
    }
    loading.value = true;
    const permissionIds = modalRef.value?.cities;
    const cb = (res: any) => {
      loading.value = false;
      const { data, error } = res;
      if (error) {
        return;
      }
      message.success(data);
      emit('refreshList');
      active.value = false;
    };
    if (props.routeId === 0) {
      createRoute({
        name,
        permissionIds
      }).then(res => {
        cb(res);
      });
      return;
    }
    updateRoute({
      name,
      id: props.routeId,
      permissionIds
    }).then(res => {
      cb(res);
    });
  });
}

// 取消
function handleCancel() {
  active.value = false;
}

// 分配按钮
function handleAssign() {
  modalRef.value?.handleShowModal({ permissionIds: permissions.value });
}

defineExpose({
  activate
});
</script>

<template>
  <NDrawer v-model:show="active" :width="502" :placement="placement">
    <NDrawerContent title="编辑角色">
      <Form
        ref="formRef"
        :form-items="formItems"
        :label-width="100"
        :model-value="unref(gatModelValue)"
        :show-submit="false"
      />
      <p>分配权限：</p>
      <Modal ref="modalRef" />
      <template #footer>
        <NButton class="mr-4" @click="handleCancel">取消</NButton>
        <NButton type="primary" :loading="loading" @click="handleSubmit">确定</NButton>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
